﻿Imports Framework.Data

Namespace FileSystemScan
    Friend Class ScanFolder_Common

        Public Shared Function GetAllFileInfosRecursive(ByVal path As String) As Generic.Dictionary(Of String, IO.FileInfo)
            Return GetAllFileInfos(path, True)
        End Function

        Public Shared Function GetAllFileInfos(ByVal path As String, ByVal recursive As Boolean) As Generic.Dictionary(Of String, IO.FileInfo)
            Dim aRet As New Generic.Dictionary(Of String, IO.FileInfo)
            If IO.Directory.Exists(path) Then AddAllFileInfosRecursive(path, aRet, recursive)
            Return aRet
        End Function

        Private Shared Sub AddAllFileInfosRecursive(ByVal currentPath As String, ByVal dict As Generic.Dictionary(Of String, IO.FileInfo), ByVal recursive As Boolean)
            For Each strFilename As String In IO.Directory.GetFiles(currentPath)
                Dim clsFI As New IO.FileInfo(strFilename)
                If IncludeFile(clsFI) Then dict.Add(strFilename.ToLower, clsFI)
            Next
            If recursive Then
                For Each strSubDir As String In IO.Directory.GetDirectories(currentPath)
                    AddAllFileInfosRecursive(strSubDir, dict, True)
                Next
            End If
        End Sub
        Friend Shared Function IncludeFile(ByVal fileInfo As IO.FileInfo) As Boolean
            If (fileInfo.Attributes And IO.FileAttributes.Hidden) = IO.FileAttributes.Hidden Then Return False
            If (fileInfo.Attributes And IO.FileAttributes.System) = IO.FileAttributes.System Then Return False
            If fileInfo.FullName.ToLower = Framework.Data.Environment.DBPath.ToLower Then Return False
            Return True
        End Function
        Friend Shared Function IncludeFile(ByVal filePath As String) As Boolean
            Return IncludeFile(New IO.FileInfo(filePath))
        End Function

        Public Const CurrentDBMediaInfoVersion As Short = 5

        Public Shared Sub EnsureMediaInfoIsUpToDate(ByVal item As Entities.SharedItem)
            Select Case item.ItemType
                Case Entities.ItemType.Movies
                    'does the item have media info?
                    If Not item.HasMediaInfo Then
                        'no, create it...
                        UpdateMediaInfoForExistingItem(item)
                        Return
                    End If
                    'ok, so we should have it. Get the media info from database...
                    Dim clsMI As Entities.MediaInfo = EntityHandlers.MediaInfo.GetBySharedItemId(item.Id)
                    If clsMI Is Nothing Then
                        'for some reason... it wasn't there...
                        UpdateMediaInfoForExistingItem(item)
                        Return
                    End If
                    If clsMI.FeatureInfoStatus = Entities.FeatureInfoStatus.MissingNeedsAction Then
                        'ok, let's retry to get the information...
                        UpdateMediaInfoForExistingItem(item)
                        Return
                    End If
                    'ok, now make sure the versions are up to date
                    'is the omx file outdated?
                    If clsMI.VersionOmxInfo < OpenMediaInfo.Manager.CurrentOmxVersion Then
                        'ok, we need to recreate the omx file
                        UpdateMediaInfoForExistingItem(item)
                    ElseIf clsMI.VersionDbInfo < CurrentDBMediaInfoVersion Then
                        'ok, so the omx file is up to date, but we need to repopulate the db tables
                        'just resave the media info
                        clsMI.VersionDbInfo = CurrentDBMediaInfoVersion
                        EntityHandlers.MediaInfo.Save(clsMI)
                    End If
            End Select
        End Sub

        Public Shared Sub UpdateMediaInfoForExistingItem(ByVal item As Entities.SharedItem)
            UpdateMediaInfoForExistingItem(item, Nothing, CreateMediaInfoMode.Normal)
        End Sub
        Public Shared Sub UpdateMediaInfoForExistingItem(ByVal item As Entities.SharedItem, ByVal mode As CreateMediaInfoMode)
            UpdateMediaInfoForExistingItem(item, Nothing, mode)
        End Sub
        Public Shared Sub UpdateMediaInfoForExistingItem(ByVal item As Entities.SharedItem, ByVal imdbHintUri As System.Uri, ByVal mode As CreateMediaInfoMode)
            Select Case item.ItemType
                Case Entities.ItemType.Movies
                    Dim clsResult As Handler_OpenMediaInfo.Result
                    clsResult = Handler_OpenMediaInfo.CreateOrUpdateMediaInfo(item, mode, imdbHintUri)
                    If clsResult IsNot Nothing Then
                        Using t As New TransactionScope
                            clsResult.MediaInfo.VersionDbInfo = CurrentDBMediaInfoVersion
                            clsResult.MediaInfo.VersionOmxInfo = clsResult.MediaInfo.OpenMediaInfo.Version
                            EntityHandlers.MediaInfo.Save(clsResult.MediaInfo, t)
                            item.HasMediaInfo = True
                            ScanFolder_Common.UpdateOmxFileInDb(item, clsResult.OmxFilePath, t)
                            t.Complete()
                        End Using
                    End If
                Case Else
                    If item.HasMediaInfo Then
                        Using t As New TransactionScope
                            item.HasMediaInfo = False
                            EntityHandlers.SharedItems.Save(item, t)
                            EntityHandlers.MediaInfo.DeleteBySharedItemId(item.Id, t)
                            t.Complete()
                        End Using
                    End If
            End Select

        End Sub

        Public Shared Sub UpdateOmxFileInDb(ByVal item As Entities.SharedItem, ByVal omxFilePath As String, ByVal transactionScope As TransactionScope)
            'get all files for the item
            Dim aFiles As Generic.List(Of Entities.SharedItemFile) = EntityHandlers.SharedItemsFiles.GetAllBySharedItemId(item.Id, transactionScope)
            Dim clsOmxFile As Entities.SharedItemFile = Nothing
            For Each clsTmpFile As Entities.SharedItemFile In aFiles
                If IO.Path.GetExtension(clsTmpFile.FileName).ToLower = ".omx" Then
                    clsOmxFile = clsTmpFile
                    Exit For
                End If
            Next
            If clsOmxFile Is Nothing Then
                clsOmxFile = New Entities.SharedItemFile
            Else
                item.TotalSize -= clsOmxFile.Size
            End If
            Dim clsFI As New IO.FileInfo(omxFilePath)
            Handler_ScanFolder.InitializeFile(clsOmxFile, item, clsFI)
            item.TotalSize += clsFI.Length
            item.LastChanged = clsFI.LastWriteTimeUtc
            EntityHandlers.SharedItemsFiles.Save(clsOmxFile, transactionScope)
            EntityHandlers.SharedItems.Save(item, transactionScope)
        End Sub
    End Class
End Namespace